package com.quyunshuo.module.home.room.database

import androidx.databinding.adapters.Converters
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.quyunshuo.edwinpro.base.BaseApplication
import com.quyunshuo.module.home.room.dao.ConcentrationDao
import com.quyunshuo.module.home.room.dao.PoetDao
import com.quyunshuo.module.home.room.dao.TargetDao
import com.quyunshuo.module.home.room.dao.VideoListCacheDao
import com.quyunshuo.module.home.room.entity.ConcentrationEntity
import com.quyunshuo.module.home.room.entity.PoetEntity
import com.quyunshuo.module.home.room.entity.TargetEntity
import com.quyunshuo.module.home.room.entity.VideoInfo

/**
 * @author mingyan.su
 * @date   2023/4/11 16:23
 * @desc   数据库操作类
 * 指定有哪些表，version必须指定版本，exportSchema生成一个json文件，方便排查问题，还需要在build.gradle文件中配置
 */
@Database(entities = [VideoInfo::class,PoetEntity::class,ConcentrationEntity::class,TargetEntity::class], version = 3, exportSchema = false)
abstract class SumDataBase : RoomDatabase() {
    //抽象方法或者抽象类标记
    abstract fun videoListDao(): VideoListCacheDao

    //抽象方法或者抽象类标记
    abstract fun poetDao(): PoetDao

    //抽象方法或者抽象类标记
    abstract fun concentrationDao(): ConcentrationDao

    //抽象方法或者抽象类标记
    abstract fun targetDao(): TargetDao

    companion object {
        private var dataBase: SumDataBase? = null

        //同步锁，可能在多个线程中同时调用
        @Synchronized
        fun getInstance(): SumDataBase {
            return dataBase ?: Room.databaseBuilder(BaseApplication.application, SumDataBase::class.java, "SumTea_DB")
                    //是否允许在主线程查询，默认是false
                    .allowMainThreadQueries()
                    //数据库被创建或者被打开时的回调
                    //.addCallback(callBack)
                    //指定数据查询的线程池，不指定会有个默认的
                    //.setQueryExecutor {  }
                    //任何数据库有变更版本都需要升级，升级的同时需要指定migration，如果不指定则会报错
                    //数据库升级 1-->2， 怎么升级，以什么规则升级
                    .addMigrations(MIGRATION_1_2,MIGRATION_2_3)
                    //设置数据库工厂，用来链接room和SQLite，可以利用自行创建SupportSQLiteOpenHelper，来实现数据库加密
                    //.openHelperFactory()
                    .build()
        }
        // 定义从版本1到版本2的迁移
        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 创建新的专注记录表
                database.execSQL("""
                CREATE TABLE IF NOT EXISTS `concentration` (
                    `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                    `duration_minutes` INTEGER NOT NULL DEFAULT 0,
                    `focus_date` TEXT NOT NULL
                )
            """)
                // 可选：添加索引以优化查询
                database.execSQL("CREATE INDEX IF NOT EXISTS `index_concentration_focus_date` ON `concentration` (`focus_date`)")
            }
        }

        // 从2到3的迁移：添加target表
        private val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 创建新的目标表
                database.execSQL("""
                    CREATE TABLE IF NOT EXISTS `target` (
                        `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
                        `content` TEXT NOT NULL DEFAULT '',
                        `status` TEXT NOT NULL DEFAULT 'ACTIVE',
                        `start_date` TEXT NOT NULL,
                        `end_date` TEXT NOT NULL
                    )
                """)

                // 添加索引
                database.execSQL("CREATE INDEX IF NOT EXISTS `index_target_content` ON `target` (`content`)")
                database.execSQL("CREATE INDEX IF NOT EXISTS `index_target_start_date` ON `target` (`start_date`)")
                database.execSQL("CREATE INDEX IF NOT EXISTS `index_target_end_date` ON `target` (`end_date`)")
            }
        }
    }



}